import { observable, action } from 'mobx';
import { WFQueryIndexStore } from './queryIndex';
import { WeaForm } from 'comsMobx';
import * as API from '../apis/customQuery';
import { WeaTableNew } from 'comsMobx'
const { TableStore } = WeaTableNew;
import isEmpty from 'lodash/isEmpty';
import * as _ from 'lodash';
import {WeaLocaleProvider, WeaTools} from 'ecCom';
import {message} from 'antd';
import * as API_SUPERVISE from '../apis/supervise';
const getLabel = WeaLocaleProvider.getLabel;

export class WFQueryResultStore extends WFQueryIndexStore{
    
    @observable viewcondition = 0;
    topTab = [];
    detailTitle = "";
    @observable hasScrollX = false;
    @observable tableStore = new TableStore();
    otherInfo = {};
    @observable showModalObj = {};

    @observable showBatchSupervisor = false;
    //关注点击按钮的位置
    @observable clickPotion={};
    @observable followTypeSelectShow = false;
    @observable FollowRequestid='';
    constructor(){
        super();
        this.switchTab = this.switchTab.bind(this);
        this.copyQueryIndexStore = this.copyQueryIndexStore.bind(this);
        this.initTopTab = this.initTopTab.bind(this);
        this.reLoad = this.reLoad.bind(this);
        this.showAllTreeNode = this.showAllTreeNode.bind(this);
        this.setSelectedTreeKey = this.setSelectedTreeKey.bind(this);
        this.doSearch = this.doSearch.bind(this);
        this.clickButttonDrop = this.clickButttonDrop.bind(this);
        this.controlShowModal = this.controlShowModal.bind(this);
        this.setShowBatchSupervisor = this.setShowBatchSupervisor.bind(this);
        this.doSupervise = this.doSupervise.bind(this);
        this.rewriteTableStore();
    }
    @action
    setClickPotion(params) {
        this.clickPotion = params;
    }
    @action
    setShowBatchSupervisor(bool = false) {
        this.showBatchSupervisor = bool;
    }

    @action
    switchTab(tabKey){
        this.viewcondition = parseInt(tabKey);
        this.doSearch();
    }

    rewriteTableStore = () =>{
        const getDatas = this.tableStore.getDatas.bind(this.tableStore);//重写组件getdatas方法，处理点击列排序、切页时不走回调
        this.tableStore.getDatas = (...arg) => {
            getDatas(arg[0], arg[1], arg[2], arg[3], (...res) => {
                this.showUnoperators(arg[4]);
            }, arg[5]);
        }
    }

    //重置所有状态
    resetAllStatus(){
        this.viewcondition = 0;
        this.topTab = [];
        this.detailTitle = "";
        this.urlParams = {};
        this.showModalObj = {};
        this.tableStore = new TableStore();
        this.rewriteTableStore();
        this.belongPathTree = true;
        this.showTreeSwitch = true;
        this.title = getLabel(386385,'查询流程');
        this.initTreeProps();
        this.resetCondition(true);
        this.setShowSearchAd(false);
    }
    
    //从查询导航页面跳转时，直接拷贝条件值
    copyQueryIndexStore(store){
        const treeProps = mobx.toJS(store.treeProps);
        if(isEmpty(treeProps)){     //树数据为空代表查询结果页做了F5刷新,刷新后默认都带树
            this.doInit();
            if(this.urlParams.isPreview === "true")
                this.changeCustomid(this.urlParams.customid);
            return;
        }
        this.belongPathTree = store.belongPathTree;
        if((this.belongPathTree && treeProps.pathTree.length === 0) || (!this.belongPathTree && treeProps.kindTree.length === 0)){
            this.loadTree(true);    //导航页树没加载完立刻点搜索情况
        }else{
            this.treeProps = treeProps;
        }
        this.operBtnKey = store.operBtnKey;
        //常用条件
        this.fixedCondition = store.fixedCondition;
        this.fixedForm.initFormFields(store.fixedCondition);
        const fixedValues = store.fixedForm && store.fixedForm.getFormDatas() || {};
        this.fixedForm.updateFields(fixedValues, true);
        //自定义条件
        this.customid = store.customid;
        this.customOption = store.customOption;
        if(store.customCondition && store.customCondition.length > 0){
            this.customCondition = store.customCondition;
            this.customForm = new WeaForm();
            this.customForm.initFormFieldObj(store.customCondition);
            const customValues = store.customForm && store.customForm.getFormDatas() || {};
            this.customForm.updateFields(customValues, true);
        }
    }

    initTopTab(){
        this.topTab = [{title: getLabel(18874,"直接参与"), viewcondition: 0},{title: getLabel('26469','我的关注'), viewcondition: 2},{title: getLabel(386387,"共享给我"), viewcondition: 1},];
    }

    setDetailTitle(){   //计算二级标题
        let detailTitle = "";
        const selectedKey = this.treeProps.selectedKey || "";
        if(this.belongPathTree){     //取高级搜索中路径名称
            const fixedFormDatas = this.fixedForm.getFormDatas() || {};
            const wfObj = "workflowid" in fixedFormDatas ? fixedFormDatas.workflowid : {};
            const valueArr = "valueObj" in wfObj ? wfObj.valueObj : [];
            valueArr && valueArr.map(v =>{
                detailTitle += "，"+v.name;
            });
            if(detailTitle !== "")
                detailTitle = detailTitle.substring(1);
        }else{      //取树中查询种类名称
            this.treeProps.kindTree && this.treeProps.kindTree.map(t =>{
                t.childs && t.childs.map(w =>{
                    if(w.domid === selectedKey)
                        detailTitle = w.name;
                });
            });
        }
        if(detailTitle !== "")
            detailTitle = "（"+detailTitle+"）";
        this.detailTitle = detailTitle;
    }

    reLoad(params={}){
        if(params.from === "openReq")
            return;
        const current =  this.tableStore.current;
		const sortParams = this.tableStore.sortParams.toJS();
        this.doSearch({current, sortParams});
    }

    showAllTreeNode(){
        this.fixedForm && this.fixedForm.resetConditionValue();
        this.clearCustomCondition(true);
        super.showAllTreeNode();
        this.doSearch();
    }

    setSelectedTreeKey(key){
        this.resetCondition(false);
        super.setSelectedTreeKey(key, ()=>{
            this.doSearch();
        });
    }
    
    doSearch(params = {}){
        this.loadCustomConditionCallback = null;
        this.setShowSearchAd(false);
        //常用查询条件值
        const fixedSearchParams = this.fixedForm ? this.fixedForm.getFormParams() : {};
        //自定义查询条件值
        let customSearchParams = {};
        this.setDetailTitle();
        this.hasScrollX = !!this.customid;
        if(!!this.customid){
            let customConditionMap = {};
            this.customCondition.map(v =>{
                customConditionMap[v.otherParams.fieldid] = v;
            });
            let customfields = "";
            let customFormParams = this.customForm ? this.customForm.getFormParams() : {};
            const reg = new RegExp("^(custom_)(\\d+)_");    //正则分组
            for(const key in customFormParams){
                customSearchParams[key] = customFormParams[key];
                if(reg.test(key)){      //自定义查询条件值
                    const fieldid = RegExp.$2;
                    if(`,${customfields},`.indexOf(`,${fieldid},`) === -1)
                        customfields +=  ","+fieldid;
                    //部分类型字段，置默认值
                    const condition = customConditionMap[fieldid];
                    const htmltype = condition.otherParams.htmltype;
                    const detailtype = condition.otherParams.detailtype;
                    if((htmltype === 1 && detailtype === 1) || htmltype === 2){
                        customSearchParams[`custom_${fieldid}_opt`] = "3";     //包含
                    }else if(htmltype === 1 && detailtype !== 1){
                        customSearchParams[`custom_${fieldid}_opt`] = "2";     //大于或等于
                        customSearchParams[`custom_${fieldid}_opt1`] = "4";    //小于或等于
                    }else if(htmltype === 3 && (detailtype === 2 || detailtype === 19)){
                        customSearchParams[`custom_${fieldid}_opt`] = "2";     //大于或等于
                        customSearchParams[`custom_${fieldid}_opt1`] = "4";    //小于或等于
                    }else if(htmltype === 3 && condition.conditionType === "BROWSER"){
                        customSearchParams[`custom_${fieldid}_opt`] = "1";     //包含
                    }
                }
            }
            customSearchParams["customid"] = this.customid || "";
            customSearchParams["customfields"] = customfields;
        }
        //拼接查询请求全部参数
        // let filterUrlParams = {};
        // const allowRange = ["jsonstr", "offical", "officalType", "requestname", "workflowid", "typeid", "docids"];
        // Object.keys(this.urlParams).map(key =>{
        //     if(_.indexOf(allowRange, key) > -1 || key.indexOf("cus_") === 0)
        //         filterUrlParams[key] = this.urlParams[key];
        // });
        const queryParams = {...{viewcondition:this.viewcondition,operBtnKey:this.operBtnKey,belongPathTree:this.belongPathTree}, ...this.urlParams, ...fixedSearchParams, ...customSearchParams};
        this.loading = true;
        API.getQueryResultKey(queryParams).then(data=>{
            this.loading = false;
            this.otherInfo = data.otherInfo;
            this.tableStore.getDatas(data.sessionkey, params.current || 1, "", params.sortParams || []);
        });
    }

    showUnoperators(callback){
        if(callback && typeof(callback) === 'function'){
            callback();//原tablestore的callback
        }
        let newDatas = [];//[{requestid:1,userid:1,unoperators:1},{requestid:2,userid:2,unoperators:2}]
        if(this.tableStore.datas){
            this.tableStore.datas.map(data => {
                newDatas.push({"requestid":data.requestid,"userid":data.userid,"unoperators":data.unoperators});
            })
        }
        API.getUnoperators({datas:JSON.stringify(newDatas),actiontype:'batch',showAll:'false'}).then(unoperators =>{
            for(var unopt in unoperators){
                jQuery("#"+unopt).html(unoperators[unopt]);
            }
        });
    }

    clickButttonDrop(key){
        this.tableStore.tableUpdate({checkId:key, selectedRowKeys:[]});
        this.tableStore.reloadCurrent(()=>{
            this.operBtnKey = key;
        });
    }

    controlShowModal(key, bool=false){
        this.showModalObj = {...this.showModalObj, ...{[key]: bool}};
    }

    @action('流程督办')
    doSupervise(params = {}){
        message.loading(getLabel(387110,'督办中...，请稍候'),0);
        API_SUPERVISE.doSupervise(params).then((data)=>{
        message.destroy();
        if(data.result){
            this.handleParams = {};
            message.success(getLabel(387108,'督办成功'));
            this.reLoad();
        }else{
            message.error(getLabel(387109,'督办失败'));
        }
        });
    }


}